package com.UKIT.airtickets.Activities

import android.content.Intent
import android.os.Bundle
import android.widget.AdapterView
import androidx.appcompat.app.AppCompatActivity
import com.UKIT.airtickets.Service.LanguageManager
import com.UKIT.airtickets.Service.Handlers.SettingsHandler
import com.UKIT.airtickets.databinding.SettingsBinding

class SettingsActivity : AppCompatActivity() {
    private lateinit var binding: SettingsBinding
    private lateinit var settingsHandler: SettingsHandler

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = SettingsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        settingsHandler = SettingsHandler(this)

        setupListeners()
    }

    private fun setupListeners() {
        binding.changePassword.setOnClickListener {
            val oldPassword = binding.oldPasswordInput.text.toString()
            val newPassword = binding.newPasswordInput.text.toString()
            settingsHandler.changePassword(oldPassword, newPassword)
        }

        binding.backButton.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        }

        binding.changeLanguage.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: android.view.View?, position: Int, id: Long) {
                val selectedLanguage = parent?.getItemAtPosition(position).toString()
                when (selectedLanguage) {
                    "English" -> {
                        if (LanguageManager.isLanguageChanged(this@SettingsActivity, "en")) {
                            settingsHandler.changeLanguage("en")
                            recreate()
                        }
                    }

                    "Русский" -> {
                        if (LanguageManager.isLanguageChanged(this@SettingsActivity, "ru")) {
                            settingsHandler.changeLanguage("ru")
                            recreate()
                        }
                    }
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
    }
}
